<template>
    <a-space style="margin-bottom: 10px">
        任务状态
        <a-radio-group v-model:value="getParams.status" option-type="button" :options="ruleStatusOptions3" />
        用户<a-select style="width: 100px" :options="userOptions" v-model:value="getParams.uid"> </a-select>
        源语言<a-select style="width: 100px" :options="langOptions.concat({ label: '请选择', value: 0 })"
            v-model:value="getParams.source_lang"> </a-select>
        目标语言<a-select style="width: 100px" :options="langOptions.concat({ label: '请选择', value: 0 })"
            v-model:value="getParams.target_lang"> </a-select>
        <a-input placeholder="输入任务名..." v-model:value="getParams.search" style="width: 150px"></a-input>
        <a-button type="primary" @click="searchFunc" :loading="searchLoading">
            <template #icon>
                <SearchOutlined />
            </template>
            搜索
        </a-button>
    </a-space>
    <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 20px;">
            <blockquote style="user-select: none">
                翻译文章总数:
                <a-typography-text strong type="warning">
                    {{ sum }}
                </a-typography-text>
                今日翻译文章数:
                <a-typography-link strong>
                    {{ today }}
                </a-typography-link>
                <reload-outlined @click="getDeeplCount" :spin="reloadSpin" style="font-size: 14px; margin-left: 15px" />
            </blockquote>
        <a-space   v-if="useAdminShow()">
            <a-popconfirm title="确定操作吗?" ok-text="确定" cancel-text="取消" @confirm="startRun">
                <a-button type="primary">开启后台程序 </a-button>
            </a-popconfirm>
            <a-popconfirm title="确定操作吗?" ok-text="确定" cancel-text="取消" @confirm="stopRun">
                <a-button type="dashed" danger>关闭后台程序 </a-button>
            </a-popconfirm>
            <a-button type="dashed" @click="showDeeplClientDetail">查看deepl客户端翻译详情</a-button>

            <a-popconfirm title="确定操作吗?" v-show="useAdminShow()" ok-text="确定" cancel-text="取消" @confirm="bulkDelete">
                <a-button type="dashed" danger>选中删除</a-button>
            </a-popconfirm>
        </a-space>
    </div>


    <a-spin :style="spinStyle" :spinning="tableLoading">
        <a-table :columns="columns" @change="handleTableChange" :row-selection="rowSelection"
            :rowKey="(row: any) => row.id" :data-source="tableData" sticky bordered :scroll="{ x: 1500 }"
            :pagination="false" size="small" class="table">
        </a-table>
        <br />
        <a-row justify="center" v-if="total > 10">
            <a-pagination v-model:current="getParams.page" v-model:pageSize="getParams.size" show-quick-jumper
                showSizeChanger :total="total" @change="pageChange" :show-total="(total: number) => `总计 ${total} 项`" />
        </a-row>

        <a-modal v-model:open="showDeeplClientDetailVisible" :title="'今日deepl客户端翻译数量——' + deeplClientSum" `>
            <p v-for="value, key in deeplClientCount">
                {{ key }} : <b style="font-weight: 700;">{{ value }}</b>
            </p>
        </a-modal>
    </a-spin>
</template>

<script lang="ts" setup>
import { SearchOutlined, ReloadOutlined } from "@ant-design/icons-vue";
import {
    startDeeplRunApi,
    stopDeeplRunApi,
    deeplTranslateTaskApi,
    getDeeplTaskResidueNumApi,
    getDeeplCountApi,
    getDeeplClientCountApi
} from "@/api/wyc";
import { useSpinLoadingState } from "@/hooks/useCommon";
import { useCommonStaticOptions } from "@/hooks/useEsArticleCommon";
import { useColumns, langOptions } from "@/hooks/wyc/useCommon";
import { message } from "ant-design-vue";
import { useAdminShow } from "@/hooks/useCommon";
const { spinStyle, viewLoading: tableLoading } = useSpinLoadingState();
const { ruleStatusOptions3 } = useCommonStaticOptions();
const { columns, isReloadData, userOptions } = useColumns(deeplTranslateTaskApi, getDeeplTaskResidueNumApi, 0);

// 表格数据
const tableData = ref<Array<AITaskList>>([]);
// 控制搜索按钮加载
const searchLoading = ref(false);
// 任务总数
const total = ref(0);
const sortObj = {
    order: "",
    sort_field: ""
};
const getParams = reactive<GetDeeplTranslateTaskParams>({
    uid: 0,
    size: 10,
    page: 1,
    search: "",
    status: 0,
    target_lang: 0,
    source_lang: 0
});
const pageChange = (pageNumber: number) => {
    getParams.page = pageNumber;
    searchFunc();
};
const selectedRowKeys = ref<Array<number>>();
const rowSelection = ref({
    checkStrictly: false,
    onSelect: (_: boolean, __: boolean, selectedRows: Array<Record<string, any>>) => {
        selectedRowKeys.value = selectedRows.map((item) => item["id"]);
    },
    onSelectAll: (_: boolean, __: boolean, selectedRows: Array<Record<string, any>>) => {
        selectedRowKeys.value = selectedRows.map((item) => item["id"]);
    }
});
// 表格排序发生改变
const handleTableChange = (pag: any, filters: any, sorter: any) => {
    if (sorter.order) {
        sortObj.order = sorter.order.slice(0, sorter.order.length - 3);
        sortObj.sort_field = sorter.field;
    } else {
        sortObj.order = "";
    }
    searchFunc();
};
const searchFunc = () => {
    searchLoading.value = true;
    tableLoading.value = true;
    // 避免page和size 大于总数
    if ((getParams.page || 1) * (getParams.size || 10) > total.value) {
        getParams.page = Math.floor(total.value / (getParams.size || 10)) + 1;
    }
    deeplTranslateTaskApi("get", { ...getParams, ...sortObj })
        .then((res) => {
            if (res.data.code === 200) {
                tableData.value = res.data.data;
                total.value = res.data.total;
            } else {
                message.error("加载失败!");
            }
        })
        .catch(() => {
            message.error("加载失败!");
        })
        .finally(() => {
            isReloadData.value = false;
            searchLoading.value = false;
            tableLoading.value = false;
            getDeeplCount();
        });
};
const bulkDelete = () => {
    selectedRowKeys.value?.forEach((id) => {
        // 批量删除
        deeplTranslateTaskApi("delete", { id })
            .then((res) => {
                if (res.data.code === 200) {
                    message.success("删除成功!");
                    isReloadData.value = true;
                    return;
                }
            })
            .catch(() => message.error("删除失败!"));
    });
};

const startRun = () => {
    startDeeplRunApi()
        .then((res) => {
            if (res.data.code === 200) {
                message.success("操作成功!");
            }
        })
        .catch((res) => {
            message.error(res.data.msg);
        });
};
const stopRun = () => {
    stopDeeplRunApi()
        .then((res) => {
            if (res.data.code === 200) {
                message.success("操作成功!");
            } else {
                message.error(res.data.msg);
            }
        })
        .catch((e) => {
            message.error(e.data.msg);
        });
};

const deeplClientSum = computed(() => {
    return Object.values(deeplClientCount.value).reduce((p, c) => {
        return p + Number(c)
    }, 0)
})
const deeplClientCount = ref<Record<string, number>>({})
const showDeeplClientDetailVisible = ref(false)
const showDeeplClientDetail = () => {
    getDeeplClientCountApi().then(res => {
        showDeeplClientDetailVisible.value = true
        deeplClientCount.value = res.data.data
        message.success("刷新成功!")
    })
}
const today = ref(0);
const sum = ref(0);
const reloadSpin = ref(false);
const getDeeplCount = () => {
    reloadSpin.value = true;
    getDeeplCountApi()
        .then((res) => {
            sum.value = res.data.deepl_sum;
            today.value = res.data.today_sum;
        })
        .finally(() => {
            reloadSpin.value = false;
        });
};


onMounted(() => {
    searchFunc();
});
</script>

<style scoped lang="scss"></style>
